package com.eranga.project;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.format.Time;
import android.util.Log;
import android.widget.Toast;

import com.eranga.project.control.data.AreaDS;
import com.eranga.project.control.data.LogDS;
import com.eranga.project.model.*;

public class PolygonLogic {

	Context context;
	public Time t2,t1;
	public long diff=-1;
	
	
	public PolygonLogic(Context context) {
		this.context = context;

	}

	public boolean givenCoordinateIsInside(double kmphSpeed,Boolean polygonStatus,
			double lat, double lng,int id) {
		
			AreaDS areaDS =new AreaDS(context);
			com.eranga.project.model.Log log =new com.eranga.project.model.Log();
			DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			Date date = new Date();
			
			LogDS logDS=new LogDS(context);
			
			String SETTINGS = "SETTINGS";
			SharedPreferences localSP = context.getSharedPreferences(SETTINGS, Context.MODE_WORLD_READABLE+ Context.MODE_WORLD_WRITEABLE);
						
		
			t1 = new Time();
			t1.setToNow();
						
			if(diff==-1 || diff < 30){
				t2 = new Time();
				t2.setToNow();
			}
				
			
		//for (PolygonValue polygonValue : polygon) {

			if(polygonStatus){
				ArrayList<Area> arrList=areaDS.getAllAreaById(id);
				String AreaName =arrList.get(0).getAreaName().toString();
				double speedLimit = arrList.get(0).getSpeedLimit();
				
				if(kmphSpeed>speedLimit)
				{
					
					diff = TimeUnit.MILLISECONDS.toSeconds(t2.toMillis(true)-t1.toMillis(true));
					Log.v("time in second", diff+"");
					
					Toast.makeText(context,"Area Name :"+AreaName+" Speed Limit:"+speedLimit, Toast.LENGTH_SHORT).show();
					
					
					try{
					
					log.setArea(AreaName);
					log.setLat(lat);
					log.setLon(lng);
					log.setDateTime(dateFormat.format(date));
					log.setSpeed(kmphSpeed);
					log.setDriver_id(localSP.getString("driver_id", ""));
					log.setStatus("High Speed");
					
					int result=logDS.createStatus(log);
					
					} catch (Exception e) {
						// TODO: handle exception
					}
					
					return true;

				}
				
				
				
		//	}
			
			//Toast.makeText(context,"Status"+ isInside(polygonValue.getPolygon(), new Point(lat, lng)), Toast.LENGTH_SHORT).show();
		}

		return false;
	}

	public static boolean isInside(Polygon polygon, Point point) {
		return polygon.contains(point);
	}

}
